package watchdog

import (
	"context"
	"time"
)

type Handler func(ctx context.Context)

func New(ctx context.Context, duration time.Duration, handler Handler) context.CancelFunc {
	c, cancel := context.WithCancel(ctx)
	go func() {
		for {
			select {
			case <-ctx.Done():
				return
			default:
				watchDogLoop(c, duration, handler)
			}
		}
	}()
	return cancel
}

func watchDogLoop(ctx context.Context, d time.Duration, handler Handler) {
	defer func() {
		if e := recover(); e != nil {
			return
		}
	}()

	if d > 0 {
		for {
			select {
			case <-ctx.Done():
				return
			case <-time.After(d):
				handler(ctx)
			}
		}
	} else {
		for {
			select {
			case <-ctx.Done():
				return
			default:
				handler(ctx)
			}
		}
	}
}
